require 'active_support'
require 'action_controller'

BASE_DIR = File.dirname(__FILE__)
require BASE_DIR + '/i_helpers/active_record/validations'

module IHelpers
  
  mattr_accessor :title_format, :title_print_in_place, :small_icons_location
  
  self.small_icons_location = "icons/small/"
  self.title_format = "$title - $sitename"
  self.title_print_in_place = true
  
  def focus_on id
    javascript_tag "$('#{id}').focus()";
  end
  
  def n2br(str)
    str.gsub("\n", "<br />")
  end
  
  def javascript(*files)
    options = files.extract_options!
    options.reverse_merge! :placement => :head
    content_for(options[:placement]) { javascript_include_tag(*files) }
  end
  
  def stylesheet(*files)
    options = files.extract_options!
    options.reverse_merge! :placement => :head
    content_for(options[:placement]) { stylesheet_link_tag(*files) }
  end
  
  # New version inspired by
  # title_helper: http://github.com/DefV/title_helper/tree/master
  def title(*args)
    options = args.extract_options! || {}
    
    options.delete([:page, :bar]) # for (at least a bit of) backwards compatibility
    
    if args.length > 0
      in_place_title = args[0]
      @title = in_place_title.gsub(/<\/?[^>]*>/, "")
      if IHelpers.title_print_in_place
        options[:class] = [options[:class], 'error'].compact.join(' ') if options[:error]
        return content_tag(:h1, [options[:header], in_place_title, options[:trailer]].compact.join(' '), options.except(:error, :header, :trailer))
      end
    else
      sitename = options[:site_name]
      if @title && !sitename.blank?
        return IHelpers.title_format.gsub('$title', h(@title)).gsub('$sitename', h(sitename))
      elsif @title && sitename.blank?
        return h(@title)
      else
        return "#{sitename}"
      end
    end
  end
  
  def small_icon(icon, options = {})
    options.reverse_merge! :class => "icon"
    prefix = IHelpers.small_icons_location
    if options[:grayed_out]
      options.delete :grayed_out
      prefix += "grayed_out/"
    end
    image_tag("#{prefix}#{icon}.png" , options)
  end
  
  def link_with_icon_to(options = {})
    r = link_with_icon(options)
    options[:link_options].reverse_merge!(:class => "with_icon")
    r = link_to(r, options[:url], options[:link_options]) if !options[:disabled]
    r
  end
  
  def link_with_icon_to_remote(options = {})
    r = link_with_icon(options)
    options.reverse_merge!(:link_html_options => {})
    options.reverse_merge!(:method => :post)
    options[:link_options].reverse_merge!({:method => options[:method]})
    options[:link_html_options].reverse_merge!(:class => "with_icon")
    r = link_to_remote(r, {:url => options[:url]}.merge(options[:link_options]),
      options[:link_html_options]) if !options[:disabled]
    r
  end
  
  def flash_tag
    r = ""
    notice_style = "display: none;" if !flash[:notice]
    error_style = "display: none;" if !flash[:error]
    r << content_tag(:div, flash[:notice], {:id => "flash_notice", :style => notice_style})
    r << content_tag(:div, flash[:error], {:id => "flash_error", :style => error_style})
  end
  
  def update_flash  
    r = ""
    update_page do |page|
      if flash[:notice]
        r << (page.replace_html :flash_notice, flash[:notice])
        r << (page.show :flash_notice)
        flash.discard :notice
      end
      if flash[:error]
        r << (page.replace_html :flash_error, flash[:error])
        r << (page.show :flash_error)
        flash.discard :error
      end
    end
    r
  end
  
  def discard_flash
    r = ""
    update_page do |page|
      r << (page.replace_html :flash_notice, nil)
      r << (page.hide :flash_notice)
      flash.discard :notice if flash[:notice]
      r << (page.replace_html :flash_error, nil)
      r << (page.hide :flash_error)
      flash.discard :error if flash[:error]
    end
    r
  end
  

  protected
  def link_with_icon(options = {})
    options.symbolize_keys!
    options.reverse_merge!(:show_text => true, :show_icon => true, :disabled => false,
      :icon_options => {}, :link_options => {}, :text_options => {})
    options[:icon_options].reverse_merge!(:alt => options[:text])
    if options[:disabled]
      options[:icon_options].reverse_merge!(:grayed_out => true)
      options[:text_options].reverse_merge!(:class => "icon_text_grayed_out")
    else
      options[:text_options].reverse_merge!(:class => "icon_text")
    end
    return "" unless options.has_key?(:icon) || options.has_key?(:text)
    
    r = ""
    r << small_icon(options[:icon], options[:icon_options]) if options[:show_icon]
    r << content_tag(:span, options[:text], options[:text_options]) if options[:show_text] && options[:text]
    r
  end
end

require 'i_helpers/active_record/validations'

ActionController::Base.helper IHelpers

class ActiveRecord::Base
  include IHelpers::ActiveRecord::Validations
end

# Load locales from +locale+ directory into Rails
I18n.load_path += Dir[ File.join(File.dirname(__FILE__), 'locale', '*.{rb,yml}') ]